'''
Author: fwz
e-mail: wz-fu@qq.com
Date: 2023-03-15 19:04:49
LastEditTime: 2023-03-15 21:42:01
Description: 自动检测下载chromeDriver
'''

import os
import re
from selenium import webdriver
import requests
import json
import zipfile
import shutil

# python地址
pythonPath = r'D:\python'
ChromePath = r'C:\Program Files\Google\Chrome\Application'


# 获取chrom版本
def getVersiom():
    try:
        option = webdriver.ChromeOptions()
        option.add_argument('--headless')  # 无界面
        webdriver.Chrome(options=option)
    except Exception as msg:
        print("ChromeWebDriver异常：" + str(msg))
        reg = "Current browser version is.+with"
        chrome_version = re.search(reg, str(msg)).group().replace(
            "Current browser version is ", "").replace(" with", "")
        print("Chrome Version:" + chrome_version)
        return chrome_version[:-3]
    return True


# 下载对应版本的chromeDriver
def download(Version):
    url = 'https://registry.npmmirror.com/-/binary/chromedriver/'
    response = requests.get(url, verify=False)
    json_drivers = json.loads(response.text)
    for data in json_drivers:
        if data['name'][:-4] == Version:
            url = data['url']
            version = data['name'][:-1]
    url += 'chromedriver_win32.zip'
    down = requests.get(url)
    filename = r'./' + 'chromedriver_' + version + '.zip'
    savename = r'./'
    open(file=filename, mode='wb').write(down.content)
    # 解压文件
    file = zipfile.ZipFile(filename)
    file.extractall(savename)
    file.close()
    # 移动文件
    os.remove(filename)
    shutil.copy2(r'./chromedriver.exe', ChromePath)
    shutil.copy2(r'./chromedriver.exe', pythonPath)
    if os.path.exists(r'./LICENSE.chromedriver'):
        os.remove(r'./LICENSE.chromedriver')
    os.remove(r'./chromedriver.exe')


Version = getVersiom()
if Version is True:
    print("chrmoeDriver版本正确")
else:
    download(Version)
    print("已载最新版")
